#pragma once

#include <iostream>
#include <memory>
#include <csignal>
#include <unistd.h>
#include <sys/wait.h>
#include <cstdlib>
#include <string>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <thread>
#include <functional>

#include <sys/types.h>
#include "softbus_common.h"
#include "nativetoken_kit.h"
#include "token_setproc.h"
#include "device_manager.h"
#include "dm_constants.h"
#include "socket.h"
#include "trans_type.h"
#include <nlohmann/json.hpp>
#include <cctype>
#include <algorithm>
#include <sstream>

class MySelfScenarioBasedTesting {
public:
    // 消息队列相关
    struct Message {
        int32_t socket;
        std::vector<uint8_t> data;
        uint32_t len;
    };
    // 消息返回
    struct ReturnMessage {
        int32_t socket;
        nlohmann::json jsonData;
    };

    // 删除拷贝构造函数和赋值操作符
    MySelfScenarioBasedTesting(const MySelfScenarioBasedTesting&) = delete;
    MySelfScenarioBasedTesting& operator=(const MySelfScenarioBasedTesting&) = delete;

    // 获取单例实例的静态方法
    static MySelfScenarioBasedTesting& getInstance();

    // 初始化软总线并监听套接字
    int32_t init();

    // 资源清理函数（可选，显式释放资源）
    static void cleanup();

    // 启动线程延后处理队列消息
    void startMessageProcessingThread();

    // 停止后台线程
    void stopMessageProcessingThread();

    // 启动发送线程后处理队列消息
    void startMessageSendThread();

    // 停止发送线程
    void stopMessageSendThread();

    //重启
    void rebootDevice(int32_t socket, std::string method);

protected:
    // 将构造函数设为 protected 或 private
    MySelfScenarioBasedTesting() = default;

private:
    // 私有成员变量可以在这里声明
    // 软总线绑定套接字唯一会话标识，使用特定字符串开头(涉及到软总线配置文件开放权限)并拼接软总线设备 ID 的格式
    std::string sessionName = "";
    // 软总线绑定套接字包名标识
    std::string pkgName = "ohos.InterConnection.iShare";
    // 唯一缺省参数的监听套接字序号，用来接收所有绑定请求
    int32_t listeningSocket = -1;
    // 监听套接字事件回调结构体对象
    ISocketListener listener;
    // 私有添加权限函数，于初始化中最先调用
    int32_t MySelfAddPermission();
    // 初始化 DM 实例
    int32_t MySelfInitDeviceManager();
    // 获取软总线设备 ID
    int32_t MySelfGetLocalDeviceId();
    // 监听套接字
    int32_t MySelfListening();
    // 释放 DM 实例
    int32_t MySelfUnInitDeviceManager();
    // 通过套接字序号关闭套接字
    void MySelfShutdownSocket(int32_t socket);
    std::pair<std::string, int> MySelfGetTerminalOutput(const std::string& command);
    // 消息分发函数
    int32_t handleMessage(MySelfScenarioBasedTesting::Message msg);
    void getSoftbusVersion(int32_t socket, std::string method);
    void getSystemInfo(int32_t socket, std::string method);
    void getPullUpAppList(int32_t socket, std::string method);
    void pullUpTheApplication(int32_t socket, std::string method, nlohmann::json jsonData);
    void setDeviceName(int32_t socket, std::string method, nlohmann::json jsonData);
    int32_t mySelfSendMessage(int32_t socket, nlohmann::json json);


private:
    static void OnBind(int32_t socket, PeerSocketInfo info) {
        std::cout << "OnBind socket: " << socket << std::endl;
    }
    static void OnShutdown(int32_t socket, ShutdownReason reason) {
        std::cout << "OnShutdown socket: " << socket << std::endl;
    }
    static void OnMessage(int32_t socket, const void *data, uint32_t len);
    static void OnFile(int32_t socket, FileEvent *event);
    std::queue<Message> messageQueue;
    std::queue<ReturnMessage> sendQueue;
    std::mutex queueMutex;
    std::mutex sendQueueMutex;
    std::condition_variable queueCV;
    std::condition_variable sendQueueCV;
    std::thread workerThread;
    bool stopWorker = false;
    std::thread sendThread;
    bool sendStopWorker = false;

    // 处理消息的函数
    void processMessages();

    // 发送消息的函数
    void processSendMessages();

    };

// 初始化 DM 需要继承 DmInitCallback 类
class MySelfScenarioBasedTestingCallBack: public OHOS::DistributedHardware::DmInitCallback {
    // 实现 DmInitCallback 中对应的虚函数
    void OnRemoteDied() override;
};

// RAII 包装器：确保单例析构
class SingletonRAII {
public:
    SingletonRAII();
    ~SingletonRAII();
private:
    static void signalHandler(int signal);
};

// 全局 RAII 包装器（确保单例析构）
extern SingletonRAII singletonGuard;  // 声明（定义在 .cpp 中）